/* eslint-disable no-console */
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { syncTimerTask, getLaunchOptionsSync } from '@ray-js/ray';
import store from '@/redux';
import { devices, dpKit } from '@/devices';
import { DevInfo, utils } from '@ray-js/panel-sdk';
import defaultConfig from '@/config/default';

import { initCloud } from './redux/modules/cloudStateSlice';
import { updateTimerList } from './redux/modules/scheduleStateSlice';
import { CLOUD_DATA_KEYS_MAP } from './constant';

import './styles/index.less';

interface Props {
  devInfo: DevInfo;
  extraInfo?: Record<string, any>;
  preload?: boolean;
}

interface State {
  devInfo: DevInfo;
}

const composeLayout = (Comp: React.ComponentType<any>) => {
  return class PanelComponent extends Component<Props, State> {
    async onLaunch() {
      devices.lamp.init();
      devices.lamp.onInitialized(device => {
        dpKit.init(device);
        // store.dispatch(initCloudDataAsync()); // 初始化设备维度缓存的云端数据，并同步到 redux
        // this.initCloudData();

        this.initCloudData();
      });
    }

    /**
     * 初始化设备维度缓存的云端数据，并同步到 redux
     */
    async initCloudData() {
      ty.showLoading({ title: '' });
      const storageKeys = Object.values(CLOUD_DATA_KEYS_MAP);
      return Promise.all(storageKeys.map(k => devices.lamp.model.abilities.storage.get(k)))
        .then(data => {
          console.log('get saveCloudData', data);

          const clockNames = {};
          Object.values(CLOUD_DATA_KEYS_MAP).forEach((k, i) => {
            clockNames[k] = data[i]?.data?.value || '';
          });

          // TODO: move to async action
          store.dispatch(
            initCloud({
              clockNames,
            })
          );
          ty.hideLoading();
        })
        .catch(err => {
          console.log('=== storage.get failed', err);
          ty.hideLoading();
        });
    }

    render() {
      const { extraInfo } = this.props;

      return (
        <Provider store={store}>
          <Comp extraInfo={extraInfo} {...this.props} />
        </Provider>
      );
    }
  };
};

export default composeLayout;
